﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using System.Configuration;
using Newtonsoft.Json.Linq;

namespace HIS.Controllers.Master
{
    public class ItemTypes: HIS.Controllers.AppBaseController
    {
        #region Fields

        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private RefItemType refItemType = null;
        #endregion

        #region Items Types
         public ItemTypes()
        {
            Data.Add("Pagetitle", "Item Types");
            Data.Add("Notification", strNotification);
        }

        [Authorization(RoleAction = "master-items")]
        public override void Index()
        {
            try
            {
                Data["Pagetitle"] += " :: List Item Types ::";
                RenderFile("master\\itemgroups\\itemtypes.html");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        [Authorization(RoleAction = "master-items")]

        public void TableList()
        {
            try
            {

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
				string descvalue = HttpContext.Current.Request["descvalue"].NullSafeToString();
                string itemcode = HttpContext.Current.Request["itemcode"].NullSafeToString();
                
                string ssearch = "desc=" + descvalue + ";code=" + itemcode;
                //string ssearch = "desc" + descvalue;
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //pagingSearch.sSearch = HttpContext.Current.Request["sSearch"];
                if (!string.IsNullOrEmpty(ssearch))
                {
                    pagingSearch.sSearch = ssearch;
                }
                else { pagingSearch.sSearch = Convert.ToString(HttpContext.Current.Request["sSearch"]); }
                pagingSearch.sSearch = ssearch;

                string strUri = string.Empty;
                strUri = Global.ServiceUriDictionary["itemtypepaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);

            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }


        [Authorization(RoleAction = "master-items")]
        //edit oke
        public void EditTypes()
        {
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            try
            {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            }
            catch
            {
                /// Throw to list if something goes wrong
                GoToUrl("itemtypes/"); return;
            }

            try
            {
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["itemtype"] + id + Global.ServiceUriDictionary["requestformat"];
                ///Get Rest///
                stringReader = base.RestService.GetJson(strUri);
                ///Deserialize json response to object///
                refItemType= JsonConvert.DeserializeObject<RefItemType>(stringReader.ReadToEnd());
                ///Set variable for rendering on view HTML///
                Data["Pagetitle"] += " :: Edit Item Types ::";
                Data.Add("refItemType", refItemType);
                Data.Add("IsCreate", "false");
                Data.Add("Actionform", Data["rooturl"] + "master/itemtypes/edittypes/");
                Data["Notification"] = strNotification;
            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                RenderFile("Master\\itemgroups\\edittypes.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }


        [Authorization(RoleAction = "master-items")]

        //Delete belum
        public void DeleteTypes()
        {
            StringReader stringReader = null;
            int id = 0;
            try
            {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            }
            catch
            {
                GoToUrl("itemtypes/");
                return;
            }

            try
            {
                refItemType = new HISModels.Entities.RefItemType();
                string strUri = Global.ServiceUriDictionary["itemtype"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                var a = JsonConvert.DeserializeObject<RefItemType>(stringReader.ReadToEnd());
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                


                HttpContext.Current.Response.Redirect(Data["rooturl"] + "master/itemtypes/");

                //GoToUrl("groupspecialist/");

                base.RestService.Dispose();
            }
        }




        [Authorization(RoleAction = "master-items")]
        //save oke
        public void SaveItemTypes()
        {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try
            {
                refItemType = new RefItemType(); Utils.Helper.SetNullToEmptyString(refItemType);
                if (HttpContext.Current.Request["IsCreate"] != "true")
                {
                    int id = 0;
                    try
                    {
                        id = Convert.ToInt32(HttpContext.Current.Request["idem"]);
                    }
                    catch { }
                    strUri = Global.ServiceUriDictionary["itemtype"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    refItemType = JsonConvert.DeserializeObject<RefItemType>(stringReader.ReadToEnd());
                }

                refItemType.PostHandler<HISModels.Entities.RefItemType>();
                strUri = Global.ServiceUriDictionary["itemtype"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true")
                {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(refItemType));
                }
                else
                {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(refItemType));
                }
                string temp = stringReader.ReadToEnd();


                refItemType = JsonConvert.DeserializeObject<RefItemType>(temp);

                if (refItemType != null)
                {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }
                else
                {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            }
            catch (Exception ex)
            {
                //strNotification = "{\"strNotification\": \"" + ex.Message + "\"}";
                HttpContext.Current.Response.Write(ex.Message);
            }
            finally
            {

                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]

        public void CreateItemTypes()
        {
            StringReader stringReader = null;
            try
            {
                Data["Pagetitle"] += " :: Add Item Types ::";
                //refItemType = new HISModels.Entities.RefItemType() { DescValue = string.Empty, CodeValue = string.Empty};
                refItemType = new HISModels.Entities.RefItemType() { DescValue = string.Empty, CodeValue = string.Empty};
                Data.Add("refItemType", refItemType);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                RenderFile("Master\\itemgroups\\edittypes.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        #endregion

    }

}

